import Taro from '@tarojs/taro'

export function useToast() {
  const show = async (options: Taro.showToast.Option) => {
    await new Promise((resolve) => setTimeout(resolve, 1e3 / 60))

    return Taro.showToast({
      icon: 'none',
      ...options
    })
  }

  const info = async (messageOrOptions: string | Taro.showToast.Option) => {
    const options = typeof messageOrOptions === 'string' ? { title: messageOrOptions } : messageOrOptions

    return show(options)
  }

  const error = async (messageOrOptions: string | Taro.showToast.Option) => {
    const options = typeof messageOrOptions === 'string' ? { title: messageOrOptions } : messageOrOptions

    return show({
      ...options,
      icon: 'error'
    })
  }

  const success = async (messageOrOptions: string | Taro.showToast.Option) => {
    const options = typeof messageOrOptions === 'string' ? { title: messageOrOptions } : messageOrOptions

    return show({
      ...options,
      icon: 'success'
    })
  }

  const loading = (messageOrOptions?: string | Taro.showLoading.Option) => {
    const options = typeof messageOrOptions === 'string' ? { title: messageOrOptions } : messageOrOptions

    Taro.showLoading({
      ...options
    } as Taro.showLoading.Option)

    return () => {
      Taro.hideLoading()
    }
  }

  return {
    show,
    info,
    error,
    success,
    loading
  }
}
